const Router = require('koa-router');
const sanitizeHtml = require('sanitize-html');
const crypto = require('crypto');
const moment = require('moment');

const query = require('../lib/mysql');
const wrapper = require('../util/wrapper');
const checkError = require('../util/checkError');

const router = new Router();

router.prefix('/admin/lesson');

module.exports = router;

/**
 * 获取所有课程
 */
router.get('/all', async (ctx, next) => {
  let list = await query(`select l.id,l.name,l.type,l.create_time,l.openId from lesson l order by create_time DESC`);

  if (!list || list && list.affectedRows === 0) {
    ctx.body = await wrapper(new Error('请求有误.'));
    return false;
  }

  list = list.map(item => {
    item.create_time = moment(item.create_time).format('YYYY-MM-DD HH:mm');
    return item;
  });

  ctx.body = await wrapper(list);
});

/**
 * 删除某个课程
 */
router.post('/del', async (ctx, next) => {
  const { id } = ctx.request.body;
  if (!/^\d+$/g.test(id)) {
    ctx.body = await wrapper(new Error('请求有误.'));
    return false;
  }
  const delRes = await query(`delete from lesson where id=${id}`);

  if (checkError(delRes)) {
    ctx.body = await wrapper(new Error('服务异常.'));
    return false;
  }

  ctx.body = await wrapper('删除成功.');
});

/**
 * 添加课程
 * @query name
 * @query content
 */
router.post('/add', async (ctx, next) => {
  let { name, type, avatar, content } = ctx.request.body;

  if (!name || !type || !content || !avatar || Array.isArray(content) && content.length === 0) {
    ctx.body = await wrapper(new Error('请求有误.'));
    return false;
  }

  name = sanitizeHtml(name);
  content = escape(JSON.stringify(content.map(item => {
    item.content = sanitizeHtml(item.content);
    return item;
  })));

  const addRes = await query(`INSERT INTO lesson (name,type,content,avatar,create_time) VALUES ("${name}","${type}","${content}","${avatar}",SYSDATE())`);
  console.log(addRes);
  if (checkError(addRes)) {
    ctx.body = await wrapper(new Error('服务异常.'));
    return false;
  }

  const secret = `babyEnglish${addRes.insertId}`;
  const hash = crypto.createHash('md5').update(secret).digest('hex');

  const updateRes = await query(`update lesson set openId="${hash}" where id="${addRes.insertId}"`);

  if (checkError(updateRes)) {
    ctx.body = await wrapper(new Error('服务异常.'));
    return false;
  }

  ctx.body = await wrapper(hash);
});

/**
 * 修改课程
 * @query name
 * @query content
 */
router.post('/edit', async (ctx, next) => {
  let { id, name, type, avatar, content } = ctx.request.body;

  if (!id || !name || !type || !avatar || !content || Array.isArray(content) && content.length === 0) {
    ctx.body = await wrapper(new Error('请求有误.'));
    return false;
  }

  name = sanitizeHtml(name);
  content = escape(JSON.stringify(content.map(item => {
    item.content = sanitizeHtml(item.content);
    return item;
  })));

  const updateRes = await query(`update lesson set name="${name}", type="${type}", avatar="${avatar}", content="${content}", create_time=SYSDATE() where id="${id}"`);
  if (checkError(updateRes)) {
    ctx.body = await wrapper(new Error('服务异常.'));
    return false;
  }

  ctx.body = await wrapper('修改成功');
});

/**
 * 根据id获取课程信息
 */
router.get('/id/:id', async (ctx, next) => {
  let { id } = ctx.params;
  if (!id || !/^\d+$/g.test(id)) {
    ctx.body = await wrapper(new Error('请求有误.'));
    return false;
  }
  let list = await query(`select * from lesson where id="${id}"`);

  if (checkError(list) || !Array.isArray(list)) {
    ctx.body = await wrapper(new Error('服务异常.'));
    return false;
  }

  list = list.map(item => {
    item.id = id;
    item.content = unescape(item.content);
    item.create_time = moment(item.create_time).format('YYYY-MM-DD HH:mm');
    return item;
  });

  ctx.body = await wrapper(list[0]);
});
